package org.check.UI;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;

import org.check.SQL.ConnectionPool;
import org.check.Util.LoadUtil;
import org.check.VO.DBConnVO;
import org.check.VO.DBParaVO;
import org.check.loadProperties.LoadProperty;
import org.check.optimize.VO.BaseCourseUser;
import org.check.potimize.business.LoadBaseCourseUser;

public class DoQueryPanel extends JPanel {

	private DBConnVO dbConnVO;
	private ConnectionPool connPool;
	private DBParaVO dbvo = new DBParaVO();
	private List<String> colList;

	/**
	 * Create the panel.
	 * @param courseType 
	 * @param dataPreviewPanelIn 
	 * @param courseDateChooserPanelIn 
	 * @param dataDateChooserPanelIn 
	 */
	public DoQueryPanel(final QuickConfigPanel quickConfigPanel, final ColSelectPanel colSelectPanel, final String filterCourse_id, final String courseType, final DataPreviewPanel dataPreviewPanel, final DateChooserPanel dataDateChooserPanel, final DateChooserPanel courseDateChooserPanel ) {
		
		
		setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		setBackground(new Color(192, 192, 192));
		setLayout(null);

		JButton button = new JButton("查询数据库");
		button.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				try {
					dbConnVO = quickConfigPanel.loadQuickConfig(quickConfigPanel.getConfIndex());
					connPool = new ConnectionPool(dbConnVO);
					colList = colSelectPanel.getCheckedElements();
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
				initDBparaVO(dataDateChooserPanel.getStartTime(),dataDateChooserPanel.getEndTime(),courseDateChooserPanel.getStartTime(),courseDateChooserPanel.getEndTime(), courseType);
				
				LoadBaseCourseUser.loadData(dbvo, colList, connPool, filterCourse_id);
				Map<String, String> map = LoadUtil.getNameAttrMap();
				List<String> colAttr = new ArrayList<String>();					
				for (String colName : colList) {
		            String value = map.get(colName);
		            colAttr.add(value);
		        }
		        
		        String[] columns = new String[colList.size()];
		        columns = colList.toArray(columns);
		        
		        //make data
		        int dataSize = LoadBaseCourseUser.resultList.size();

		        String [][]data = new String[dataSize][colList.size()];
		        for(int i = 0; i < dataSize; i++){
		        	BaseCourseUser bcu = LoadBaseCourseUser.resultList.get(i);
		        	//int j = 0;   	
		        	Object obj = bcu;
		        	try {  
		        		for(int j = 0; j < colAttr.size(); j++){
		        			String filed = colAttr.get(j);
			        		Class clazz = obj.getClass();  
			     	        PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);  
			     	        Method getMethod = pd.getReadMethod();//���get����  
			     	  
			     	        if (pd != null) {      	  
			     	            Object o = getMethod.invoke(obj);//ִ��get��������һ��Object  
			     	            String dataLable = o==null?"0":o.toString();
			     	            data[i][j]=dataLable;
			     	        }
		        		}	                
					} catch (IntrospectionException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IllegalAccessException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IllegalArgumentException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (InvocationTargetException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		        }
		        JTable showtable = new JTable(data, columns);
				
				JScrollPane scrollPane = new JScrollPane(showtable);
			
				scrollPane.setPreferredSize(new Dimension(100,20));
				scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
				scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
				scrollPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
				scrollPane.setForeground(new Color(0, 0, 139));
				scrollPane.setBackground(Color.LIGHT_GRAY);
				showtable.setFillsViewportHeight(true);
				dataPreviewPanel.removeAll();
				dataPreviewPanel.add(scrollPane);
				dataPreviewPanel.revalidate();
				connPool = null;
			}
		});
		button.setBounds(10, 10, 110, 28);
		add(button);
	}
	public void initDBparaVO(String startDate, String endDate, String courseStartDate, String courseEndDate, String courseType) {
		dbvo.setStartDate(startDate);
		dbvo.setEndDate(endDate);
		dbvo.setCourseStartDate(courseStartDate);
		dbvo.setCourseEndDate(courseEndDate);
		dbvo.setCourseType(getSelectedType(courseType));
		dbvo.setUsername(dbConnVO.getUser());
		dbvo.setTablename("courseuser");
		dbvo.setType(dbConnVO.getDbtype());
		dbvo.setSelectedCols(getSelectCols());
		dbvo.setVersion(dbConnVO.getVersion());
	}
	public String getSelectCols(){
		String result = "";
		Properties prop = LoadProperty.loadBaseProp();
		Iterator<Entry<Object, Object>> it = prop.entrySet().iterator();          
        while(it.hasNext()){
        	Entry<Object, Object> entry = it.next(); 
        	String key = entry.getKey().toString();
        	String value = entry.getValue().toString();
        	for(String select:colList){
        		if(select.equals(key))
    				result += value + ",";
        	}
        	
        }
		if(!result.equals(""))
			result = result.substring(0, result.length()-1);
		return result;
	}
	
	public String getSelectedType(String courseType){
		Properties courseProp = LoadProperty.loadCourseTypoProp();
		String code = courseProp.getProperty(courseType);
		return code;
	}
}
